#!/bin/bash

### BEGIN INIT INFO
# Provides:          gappproxy
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2
# Default-Stop:      0 1 6
# Short-Description: Google App Engine Proxy
# Description:       A http proxy based on Google App Engine. http://code.google.com/p/gappproxy/
#                    placed in /etc/init.d.
### END INIT INFO

DESC="Google App Proxy Client Daemon"
NAME=gappproxyd
WRAPPER=/usr/bin/python2.6
DAEMON=/home/source/project-local/gappproxy/localproxy/proxy.py
DaemonCommand="$WRAPPER $DAEMON"
nonprivUser=neo

if [[ $UID -ne 0 ]]; then
  echo "become root to run this script."
  exit 1
fi

case "$1" in
	start)
		echo -n "Starting $DESC: "
		if [[ `ls -R1 /var/run/screen/ | grep $NAME` ]]; then
			echo ".. [already running]."
			exit 1
		fi
		su $nonprivUser -c "screen -dmS $NAME $DaemonCommand" || exit 2
		echo "$NAME."
		;;
	stop)
		echo -n "Stopping $DESC: "
		if [[ `ls -R1 /var/run/screen/ | grep $NAME` ]]; then
			ls -R1 /var/run/screen/ | grep $NAME | awk -F. '{ print $1 }' | xargs kill || exit 2
			echo "$NAME."
		else
			echo ".. [not running]."
			exit 1
		fi
		;;
	*)
		echo "Usage: $0 {start|stop}"
		exit 3
		;;
esac
exit 0
